﻿using Beryl.Util;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;

namespace Beryl.Model
{
    //开工记录
    public class StartWork
    {
        private static StartWork instance = null;
        private static readonly object uniqueLock = new object();

        public static StartWork Instance
        {
            get
            {
                lock (uniqueLock)
                {
                    if (instance == null)
                    {
                        instance = new StartWork();
                    }
                }
                return instance;
            }
        }
        public StartWork() { }

        public List<string> getStartWork(string data,string Data)
        {
            string name = System.Reflection.MethodBase.GetCurrentMethod().Name;
            List<string> list = new List<string>();
            try
            {
                string strPicYZ1 = "";
                string sql = string.Format(@"select cMOLotNo,QcResult,dLotQty,a.cProductDepNo,cStatusNo,a.cMatNo,cOrderNo,b.cSpecifucation from APS_ProLotOrder a join [dbo].[APS_MatData_V] b on a.cMatNo = b.cMatNo where cBarCode='{0}'",data);
                strPicYZ1 = JsonConvert.SerializeObject(CommonMethod.Instance.selectDatabase(sql));
                if (strPicYZ1.Equals("[]"))
                {
                    list.Add("此流传单号错误");
                }
                else
                {
                    list.Add(strPicYZ1);
                }
            }
            catch(Exception e)
            {
                list.Add(e.Message);
                //CommonMethod.Instance.InsertLog(name, e.Message, CommonMethod.LogType.Error, Data, "开工记录查询流传单信息错误：" + data);
                CommonMethod.Instance.InsertLog1(data, list[0], Data, CommonMethod.LogType.Error, name, "", true);
                return list;
            }
            //CommonMethod.Instance.InsertLog(name, list[0], CommonMethod.LogType.Info, Data, "开工记录查询流传单信息：" + data);
            CommonMethod.Instance.InsertLog1(data, list[0], Data, CommonMethod.LogType.Info, name, "", true);
            return list;
        }

        public List<string> getProcess(string data, string Data)
        {
            string name = System.Reflection.MethodBase.GetCurrentMethod().Name;
            List<string> list = new List<string>();
            try
            {
                string strPicYZ1 = "";
                string sql = "";
                //如果提交的数据验证手机信息无问题，则通过验证数据查询该账号的工序，并排列工序
                if (Data != "")
                {
                    Newtonsoft.Json.Linq.JArray jsonArr = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(Data);
                    string account = jsonArr[0]["账号"].ToString();
                    string sql1 = "select * from SYS_User where LoginUser = '" + account + "'";
                    string result = JsonConvert.SerializeObject(CommonMethod.Instance.selectDatabase(sql1));
                    if(result.Equals("[]"))
                    {
                        throw new Exception("获取工序查询账号失败");
                    }
                    Newtonsoft.Json.Linq.JArray jsonArr1 = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(result);
                    string accountGX = jsonArr1[0]["cOperationNo"].ToString();
                    sql = string.Format(@"select a.cOperationName,a.cOperationNo,a.cOpSeq from APS_ValidRouting a inner join APS_Operation_V b on a.cOperationNo = b.cOperationNo 
    where b.cReportFlag = 1 and a.cOrderNo ='{0}' order by case when  a.cOperationNo = '{1}' then 0 else 1 end,a.cOperationNo asc ;", data,accountGX);
                    strPicYZ1 = JsonConvert.SerializeObject(CommonMethod.Instance.selectDatabase(sql));
                }else
                {
                    sql = string.Format(@"select a.cOperationName,a.cOperationNo,a.cOpSeq from APS_ValidRouting a inner join APS_Operation_V b on a.cOperationNo = b.cOperationNo
    where b.cReportFlag = 1 and a.cOrderNo ='{0}' order by a.cOpSeq;", data);
                    strPicYZ1 = JsonConvert.SerializeObject(CommonMethod.Instance.selectDatabase(sql));
                }
                
                if (strPicYZ1.Equals("[]"))
                {
                    list.Add("查询失败");
                }
                else
                {
                    list.Add(strPicYZ1);
                }
            }
            catch(Exception e)
            {
                CommonMethod.Instance.InsertLog1(data, e.Message, Data, CommonMethod.LogType.Error, name, "", true);
                list.Add(e.Message);
                return list;
            }
            CommonMethod.Instance.InsertLog1(data, list[0], Data, CommonMethod.LogType.Info, name, "", true);
            return list;
        }

        public List<string> getSelect(string data, string Data)
        {
            string name = System.Reflection.MethodBase.GetCurrentMethod().Name;
            List<string> list = new List<string>();
            try
            {
                string strPicYZ1 = "";
                string sql = string.Format(@"select InspectionItem,'' as inputvalue,Parameter as parameter from [dbo].[QC_StandardDefinition]
    where Category='开工' and Dimension='{0}';", data);
                strPicYZ1 = JsonConvert.SerializeObject(CommonMethod.Instance.selectDatabase(sql));
                if (strPicYZ1.Equals("[]"))
                {
                    list.Add("查询工序列表失败");
                }
                else
                {
                    list.Add(strPicYZ1);
                }
            }
            catch (Exception e)
            {
                CommonMethod.Instance.InsertLog1("", e.Message, Data, CommonMethod.LogType.Error, name, "", true);
                list.Add(e.Message);
                return list;
            }
            CommonMethod.Instance.InsertLog1("", list[0], Data, CommonMethod.LogType.Info, name, "", true);
            return list;
        }

        //获取裁切标签扫描结果
        public List<string> getCQTag(string data, string Data)
        {
            string name = System.Reflection.MethodBase.GetCurrentMethod().Name;
            List<string> list = new List<string>();
            data = CommonMethod.Instance.JosnChange(data);
            Newtonsoft.Json.Linq.JArray jsonArr = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(data);
            string lotno = jsonArr[0]["da"].ToString();
            try
            {
                string strPicYZ1 = "";
                string sql = string.Format(@"select * from [dbo].[APS_ProLotOrder] where cMOLotNo= '{0}';", lotno);
                strPicYZ1 = JsonConvert.SerializeObject(CommonMethod.Instance.selectDatabase(sql));
                if(strPicYZ1.Equals("[]"))
                {
                    throw new Exception("扫描物料条码错误");
                }
                Newtonsoft.Json.Linq.JArray jsonArr1 = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(strPicYZ1);
                var k = jsonArr1[0];
                string matno = k["cMatNo"].ToString();
                string mty = "";
                if (matno.StartsWith("Y0101") || matno.StartsWith("Y0191"))
                {
                    mty = "正箔";
                }
                else if (matno.StartsWith("Y0102"))
                {
                    mty = "负箔";
                }
                else
                {
                    mty = "电解纸";
                }
                Newtonsoft.Json.Linq.JArray tableArray = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(jsonArr[0]["table"].ToString());
                for (int i = 0;i< tableArray.Count;i++)
                {
                    var k1 = tableArray[i];
                    string one = k1["parameter"].ToString();
                    if (mty.Equals("电解纸"))
                    {
                        if(one.Equals(mty) && k1["inputvalue"].ToString() == "")
                        {
                            k1["inputvalue"].Replace(k["cBatchNumber"]);
                        }
                    }
                    else
                    {
                        if(one.Equals(mty))
                        {
                            k1["inputvalue"].Replace(k["cBatchNumber"]);
                        }
                    }
                }
                //jsonArr.RemoveAt(jsonArr.Count - 1);
                string rec = JsonConvert.SerializeObject(tableArray);
                list.Add(rec);
                //LogUtil.Log(name + rec);
            }
            catch(Exception e)
            {
                CommonMethod.Instance.InsertLog1(lotno, e.Message, Data, CommonMethod.LogType.Error, name, "", true);
                list.Add(e.Message);
                return list;
            }
            CommonMethod.Instance.InsertLog1(lotno, list[0], Data, CommonMethod.LogType.Error, name, "", true);
            return list;
        }

        public List<string> getMOLotNo(string para, string Data)
        {
            string name = System.Reflection.MethodBase.GetCurrentMethod().Name;
            List<string> list = new List<string>();
            try
            {
                string strPicYZ1 = "";
                string sql = string.Format(@"select cMOLotNo,QcResult,dLotQty,cProductDepNo,cStatusNo,cMatNo,cOrderNo from APS_ProLotOrder where cMOLotNo collate Chinese_PRC_CS_AS = '{0}';", para);
                strPicYZ1 = JsonConvert.SerializeObject(CommonMethod.Instance.selectDatabase(sql));
                if (strPicYZ1.Equals("[]"))
                {
                    list.Add("批次号查询失败!");
                }
                else
                {
                    Newtonsoft.Json.Linq.JArray jsonArr = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(strPicYZ1);
                    var k = jsonArr[0];
                    if (int.Parse(k["QcResult"].ToString()) <= 3)
                    {
                        list.Add("批次号查询质检异常");
                    }
                    else
                    {
                        string num = k["cStatusNo"].ToString().Substring(1);
                        if(int.Parse(num) < 91)
                        {
                            list.Add(strPicYZ1);
                        }
                        else
                        {
                            list.Add("批次已关闭，无需报工!");
                        }
                    }
                }
            }
            catch(Exception e)
            {
                CommonMethod.Instance.InsertLog1(para, e.Message, Data, CommonMethod.LogType.Error, name, "", true);
                list.Add(e.Message);
                return list;
            }
            CommonMethod.Instance.InsertLog1(para, list[0], Data, CommonMethod.LogType.Info, name, "", true);
            return list;
        }

        public List<string> summitSW(string para, string Data)
        {
            string name = System.Reflection.MethodBase.GetCurrentMethod().Name;
            List<string> list = new List<string>();
            Newtonsoft.Json.Linq.JArray jsonArr = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(para);
            try
            {
                string sql1 = "";
                string strPicYZ1 = "";
                string cProcessCode = "";
                string sql = string.Format(@"Select PEquipment,Operator,cProcess,cProStartTime from APS_PhistoryTable where cMOLotNo = '{0}' and cProcess = '{1}' and cProEndTime is null;", jsonArr[jsonArr.Count - 1]["cMOLotNo"].ToString(), jsonArr[jsonArr.Count - 1]["cProcess"].ToString());
                strPicYZ1 = JsonConvert.SerializeObject(CommonMethod.Instance.selectDatabase(sql));
                if (strPicYZ1.Equals("[]"))
                {
                    //验证工序是否正确
                    string sqlcode = string.Format(@"SELECT * FROM [192.168.1.5].UFDATA_168_2013.dbo.sfc_operation where Description = '{0}'", jsonArr[jsonArr.Count - 1]["cProcess"].ToString());
                    var k1 = CommonMethod.Instance.selectDatabase(sqlcode);
                    var KnRow = k1.Select($"Description = '{jsonArr[jsonArr.Count - 1]["cProcess"].ToString()}'");
                    if(KnRow.Length > 0)
                    {
                        var Kn1 = KnRow[0];
                        cProcessCode = Kn1["OperationId"].ToString();
                    }else
                    {
                        throw new Exception("查询工序code失败");
                        //list.Add("查询工序code失败");
                        //return list;
                    }

                    //验证输入的设备名称是否正确
                    if(!jsonArr[jsonArr.Count - 1]["PEquipment"].ToString().Equals(""))
                    {
                        string equipment = string.Format(@"select cDeviceName,cSuperviseNo from EM_EquipmentLedger where cDepartment = '{0}' and cSuperviseNo = '{1}';", jsonArr[jsonArr.Count - 1]["cProcess"].ToString(), jsonArr[jsonArr.Count - 1]["PEquipment"].ToString());
                        string checkequipment = JsonConvert.SerializeObject(CommonMethod.Instance.selectDatabase(equipment));
                        if(checkequipment.Equals("[]"))
                        {
                            throw new Exception("输入设备错误");
                        }
                    }

                    DataTable dt = new DataTable();
                    dt.Columns.Add("cMOLotNo", typeof(String));
                    dt.Columns.Add("PEquipment", typeof(String));
                    dt.Columns.Add("Operator", typeof(String));
                    dt.Columns.Add("IMaterialsNum", typeof(String));
                    dt.Columns.Add("cProcess", typeof(String));
                    dt.Columns.Add("isSyncReport", typeof(String));
                    dt.Columns.Add("cProcessCode", typeof(String));
                    dt.Columns.Add("MaterialCode", typeof(String));
                    dt.Columns.Add("Specification", typeof(String));
                    DataRow dr;
                    dr = dt.NewRow();
                    dr["cMOLotNo"] = jsonArr[jsonArr.Count - 1]["cMOLotNo"].ToString();
                    dr["PEquipment"] = jsonArr[jsonArr.Count - 1]["PEquipment"].ToString();
                    dr["Operator"] = jsonArr[jsonArr.Count - 1]["Operator"].ToString();
                    dr["IMaterialsNum"] = jsonArr[jsonArr.Count - 1]["IMaterialsNum"].ToString();
                    dr["cProcess"] = jsonArr[jsonArr.Count - 1]["cProcess"].ToString();
                    dr["isSyncReport"] = "1";
                    dr["cProcessCode"] = cProcessCode;
                    dr["MaterialCode"] = jsonArr[jsonArr.Count - 1]["cmaterialno"].ToString();
                    dr["Specification"] = jsonArr[jsonArr.Count - 1]["specification"].ToString();

                    dt.Rows.Add(dr);
                    SqlHelper.IniConnString();
                    var connstr = SqlHelper.GetConnSting();
                    SqlHelper.ExecuteNonQueryTypedParams(connstr, "PM_OrderStart", dr); //PM_OrderStart 为存储过程名称

                    for (int i = 0;i<jsonArr.Count - 1; i++)
                    {
                        var k = jsonArr[i];
                        if (!jsonArr[0]["项目"].ToString().Equals("1"))
                        {
                            DateTime dt11 = DateTime.Now;
                            string date = dt11.ToString("yyyy-MM-dd HH:mm:ss");
                            sql1 += string.Format(@"insert into [dbo].[QC_ResultRecord](NoType, TaskNo, InspectionItem,TestValue,SampleNo,CTime,OperationName) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}');",
                            "开工", jsonArr[jsonArr.Count - 1]["cMOLotNo"].ToString(), k["项目"].ToString(), jsonArr[i]["材料批号"].ToString(), "1", date,
                             jsonArr[jsonArr.Count - 1]["cProcess"].ToString());
                            SqlHelper.ExecuteNonQuery(connstr, CommandType.Text, sql1);
                        }else
                        {
                            break;
                        }
                    }

                    DataTable dt1 = new DataTable();
                    dt1.Columns.Add("cMOLotNo", typeof(String));
                    dt1.Columns.Add("cOperationName", typeof(String));
                    DataRow dr1;
                    dr1 = dt1.NewRow();
                    dr1["cMOLotNo"] = jsonArr[jsonArr.Count - 1]["cMOLotNo"].ToString();
                    dr1["cOperationName"] = jsonArr[jsonArr.Count - 1]["cProcess"].ToString();
                    SqlHelper.ExecuteNonQueryTypedParams(connstr, "UpdateBomBatch", dr1); //checkTotal 为存储过程名称
                    list.Add("[0]");
                    //LogUtil.Log(name + "插入成功");
                }
                else  
                {
                    throw new Exception("该批次已开工,请勿重复提交");
                }
            }catch(Exception e)
            {
                CommonMethod.Instance.InsertLog1(jsonArr[jsonArr.Count - 1]["cMOLotNo"].ToString(), jsonArr[jsonArr.Count - 1]["cProcess"].ToString()+ e.Message, Data, CommonMethod.LogType.Error, name, "", true);
                list.Add(e.Message);
                return list;
            }

            CommonMethod.Instance.InsertLog1(jsonArr[jsonArr.Count - 1]["cMOLotNo"].ToString(), jsonArr[jsonArr.Count - 1]["cProcess"].ToString() + list[0], Data, CommonMethod.LogType.Info, name, "", true);
            return list;
        }
    }
}